import tkinter as tk
from tkinter import ttk, messagebox
from database import DatabaseManager
from typing import List, Dict, Optional, Tuple
import os
import sys


class SearchEmployeesWindow:
    def __init__(self, parent, icon_path="asset/OIP-C.ico"):
        self.parent = parent
        self.db = DatabaseManager()
        self.current_page = 1
        self.page_size = 10
        self.conditions = {}
        self.icon_path = icon_path  # 新增图标路径属性

        # 创建查询窗口
        self.top = tk.Toplevel(parent)
        self.top.title("职工信息查询")
        self.top.geometry("1200x700")
        self.top.protocol("WM_DELETE_WINDOW", self.on_close)

        # 设置窗口图标（新增代码）
        self._set_window_icon()

        # 创建查询条件框架（保持不变）
        self.create_search_frame()

        # 创建结果表格框架（保持不变）
        self.create_result_frame()

        # 加载初始数据（保持不变）
        self.load_data()

    def _set_window_icon(self):
        """设置窗口图标（新增方法）"""
        if not self.icon_path:
            return

        try:
            # 尝试设置窗口图标
            if sys.platform == "win32":
                self.top.iconbitmap(self.icon_path)
            else:
                # macOS/Linux使用PhotoImage方式
                img = tk.PhotoImage(file=self.icon_path)
                self.top.call('wm', 'iconphoto', self.top._w, img)

        except Exception as e:
            messagebox.showwarning("图标加载失败",
                                   f"图标加载失败：{os.path.basename(self.icon_path)}\n"
                                   f"错误详情：{str(e)}\n"
                                   f"当前路径：{os.path.abspath(self.icon_path)}")

    def create_search_frame(self):
        """ 创建查询条件输入区域 """
        search_frame = ttk.LabelFrame(self.top, text="查询条件", padding=10)
        search_frame.pack(fill=tk.X, padx=10, pady=5)

        # 精确查询：职工号
        ttk.Label(search_frame, text="职工号：").grid(row=0, column=0, padx=5)
        self.entry_employee_id = ttk.Entry(search_frame, width=15)
        self.entry_employee_id.grid(row=0, column=1, padx=5)

        # 精确查询：姓名
        ttk.Label(search_frame, text="姓名：").grid(row=0, column=2, padx=5)
        self.entry_name = ttk.Entry(search_frame, width=15)
        self.entry_name.grid(row=0, column=3, padx=5)

        # 范围查询：工资
        ttk.Label(search_frame, text="工资范围：").grid(row=1, column=0, padx=5)
        self.entry_salary_min = ttk.Entry(search_frame, width=10)
        self.entry_salary_min.grid(row=1, column=1, padx=5)
        ttk.Label(search_frame, text="至").grid(row=1, column=2, padx=5)
        self.entry_salary_max = ttk.Entry(search_frame, width=10)
        self.entry_salary_max.grid(row=1, column=3, padx=5)

        # 范围查询：年龄
        ttk.Label(search_frame, text="年龄范围：").grid(row=2, column=0, padx=5)
        self.entry_age_min = ttk.Entry(search_frame, width=10)
        self.entry_age_min.grid(row=2, column=1, padx=5)
        ttk.Label(search_frame, text="至").grid(row=2, column=2, padx=5)
        self.entry_age_max = ttk.Entry(search_frame, width=10)
        self.entry_age_max.grid(row=2, column=3, padx=5)

        # 模糊查询：学历
        ttk.Label(search_frame, text="学历：").grid(row=3, column=0, padx=5)
        self.entry_education = ttk.Entry(search_frame, width=15)
        self.entry_education.grid(row=3, column=1, padx=5)

        # 模糊查询：地址
        ttk.Label(search_frame, text="地址：").grid(row=3, column=2, padx=5)
        self.entry_address = ttk.Entry(search_frame, width=25)
        self.entry_address.grid(row=3, column=3, padx=5)

        # 查询按钮
        self.btn_search = ttk.Button(
            search_frame,
            text="执行查询",
            command=self.execute_search
        )
        self.btn_search.grid(row=4, column=0, columnspan=4, pady=10)

    def create_result_frame(self):
        """ 创建结果展示区域 """
        result_frame = ttk.LabelFrame(self.top, text="查询结果", padding=10)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 创建Treeview
        self.treeview = ttk.Treeview(
            result_frame,
            columns=self.get_columns(),
            show="headings",
            selectmode="browse"
        )

        # 配置滚动条
        vsb = ttk.Scrollbar(
            result_frame,
            orient=tk.VERTICAL,
            command=self.treeview.yview
        )
        hsb = ttk.Scrollbar(
            result_frame,
            orient=tk.HORIZONTAL,
            command=self.treeview.xview
        )
        self.treeview.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        # 布局控件
        vsb.pack(side=tk.RIGHT, fill=tk.Y)
        hsb.pack(side=tk.BOTTOM, fill=tk.X)
        self.treeview.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # 配置列标题
        for col in self.treeview["columns"]:
            self.treeview.heading(col, text=col.capitalize())
            self.treeview.column(col, width=100, anchor=tk.CENTER)

        # 创建分页控件
        pagination_frame = ttk.Frame(result_frame)
        pagination_frame.pack(fill=tk.X, pady=5)

        self.page_label = ttk.Label(pagination_frame)
        self.page_label.pack(side=tk.LEFT)

        self.btn_prev = ttk.Button(
            pagination_frame,
            text="上一页",
            command=self.prev_page,
            state=tk.DISABLED
        )
        self.btn_prev.pack(side=tk.LEFT, padx=5)

        self.btn_next = ttk.Button(
            pagination_frame,
            text="下一页",
            command=self.next_page
        )
        self.btn_next.pack(side=tk.LEFT, padx=5)

    def get_columns(self) -> List[str]:
        """ 获取需要显示的列字段 """
        return [
            "employee_id", "name", "age", "gender",
            "education", "salary", "address", "phone"
        ]

    def execute_search(self):
        """ 执行组合查询 """
        # 收集查询条件
        self.conditions = {}

        # 精确查询
        employee_id = self.entry_employee_id.get().strip()
        if employee_id:
            self.conditions["employee_id"] = employee_id

        name = self.entry_name.get().strip()
        if name:
            self.conditions["name"] = name

        # 范围查询
        salary_min = self.entry_salary_min.get().strip()
        salary_max = self.entry_salary_max.get().strip()
        if salary_min or salary_max:
            self.conditions["salary_range"] = (
                salary_min if salary_min else None,
                salary_max if salary_max else None
            )

        age_min = self.entry_age_min.get().strip()
        age_max = self.entry_age_max.get().strip()
        if age_min or age_max:
            self.conditions["age_range"] = (
                age_min if age_min else None,
                age_max if age_max else None
            )

        # 模糊查询
        education = self.entry_education.get().strip()
        if education:
            self.conditions["education"] = education

        address = self.entry_address.get().strip()
        if address:
            self.conditions["address"] = address

        # 重置分页并加载数据
        self.current_page = 1
        self.load_data()

    def load_data(self):
        """ 加载分页数据 """
        try:
            # 生成动态SQL
            where_clause, params = self.build_query()

            # 执行分页查询
            data, total = self.db.execute_paginated_query(
                self.current_page,
                self.page_size,
                where_clause,
                params
            )

            # 更新Treeview
            self.update_treeview(data)

            # 更新分页信息
            total_pages = (total + self.page_size - 1) // self.page_size
            self.page_label.config(
                text=f"第 {self.current_page} 页 / 共 {total_pages} 页"
            )
            self.btn_prev.state(["disabled" if self.current_page == 1 else "!disabled"])
            self.btn_next.state(["disabled" if self.current_page >= total_pages else "!disabled"])

        except Exception as e:
            messagebox.showerror("查询失败", f"错误信息: {str(e)}")

    def build_query(self) -> Tuple[str, tuple]:
        """ 动态构建SQL查询条件 """
        where_clauses = []
        params = []

        # 精确查询
        if "employee_id" in self.conditions:
            where_clauses.append("employee_id = %s")
            params.append(self.conditions["employee_id"])

        if "name" in self.conditions:
            where_clauses.append("name = %s")
            params.append(self.conditions["name"])

        # 范围查询
        if "salary_range" in self.conditions:
            min_salary, max_salary = self.conditions["salary_range"]
            if min_salary and max_salary:
                where_clauses.append("salary BETWEEN %s AND %s")
                params.extend([min_salary, max_salary])
            elif min_salary:
                where_clauses.append("salary >= %s")
                params.append(min_salary)
            elif max_salary:
                where_clauses.append("salary <= %s")
                params.append(max_salary)

        if "age_range" in self.conditions:
            min_age, max_age = self.conditions["age_range"]
            if min_age and max_age:
                where_clauses.append("age BETWEEN %s AND %s")
                params.extend([min_age, max_age])
            elif min_age:
                where_clauses.append("age >= %s")
                params.append(min_age)
            elif max_age:
                where_clauses.append("age <= %s")
                params.append(max_age)

        # 模糊查询
        if "education" in self.conditions:
            where_clauses.append("education LIKE %s")
            params.append(f"%{self.conditions['education']}%")

        if "address" in self.conditions:
            where_clauses.append("address LIKE %s")
            params.append(f"%{self.conditions['address']}%")

        # 组合WHERE子句
        where_clause = "WHERE " + " AND ".join(where_clauses) if where_clauses else ""
        return where_clause, tuple(params)

    def update_treeview(self, data: List[Dict]):
        """ 更新Treeview显示内容 """
        # 清空现有数据
        for item in self.treeview.get_children():
            self.treeview.delete(item)

        # 插入新数据
        columns = self.get_columns()
        for row in data:
            values = [str(row[col]) for col in columns]
            self.treeview.insert(
                "",
                tk.END,
                values=values,
                tags=("even", "odd")[len(values) % 2]
            )

    def prev_page(self):
        """ 上一页 """
        if self.current_page > 1:
            self.current_page -= 1
            self.load_data()

    def next_page(self):        #在这里连接池数量不够
        """ 下一页 """
        try:
            # 获取查询条件和参数
            where_clause, params = self.build_query()

            # 计算总记录数（传递参数）
            total = self.db.get_search_count(where_clause, params)

            total_pages = (total + self.page_size - 1) // self.page_size
            if self.current_page < total_pages:
                self.current_page += 1
                self.load_data()
        except Exception as e:
            messagebox.showerror("分页失败", f"错误信息: {str(e)}")

    def on_close(self):
        """ 窗口关闭处理 """
        if hasattr(self, 'db'):
            self.db.close()  # 调用修改后的close方法
        self.top.destroy()  # 销毁Tkinter窗口


